import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Balloon, Tag } from '@teamix/ui';
import { Section, YunxiaoIcon, Title, YunxiaoTable } from '@alife/devops-ui';
import PushRuleDialog from './pushRuleDialog';
// import EditPushRule from './editPushRule';
import DeleteConfirm from 'components/deleteConfirm';
import ListEmpty from 'atComponents/ListEmpty';
import ListLoading from 'atComponents/ListLoading';
import { enterPage, Perf } from 'utils/track';
import * as actions from '../actions/index';
import '../index.scss';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;
const { Tooltip } = Balloon;

const commitCheckRuleObj = {
  CommitAuthorChecker: intl.get({
    id: 'code-assets.settingsPushRules.containers.root.CheckAuthor',
    defaultMessage: '检查作者',
  }),
  CommitCommitterChecker: intl.get({
    id: 'code-assets.settingsPushRules.containers.root.CheckSubmitter',
    defaultMessage: '检查提交者',
  }),
};

const commitCheckLevelObj = {
  warn: intl.get({
    id: 'code-assets.settingsPushRules.containers.root.WarningOnlyPushAllowed',
    defaultMessage: '仅警告，允许推送',
  }),
  block: intl.get({
    id: 'code-assets.settingsPushRules.containers.root.NoPush',
    defaultMessage: '禁止推送',
  }),
};

const prehookCheckLevelObj = {
  block: intl.get({
    id: 'code-assets.settingsPushRules.containers.root.VerificationFailed',
    defaultMessage: '验证不通过',
  }),
  warn: intl.get({
    id: 'code-assets.settingsPushRules.containers.root.IgnoreTheRuleAndVerify',
    defaultMessage: '忽略规则，验证通过',
  }),
};

class Root extends Component {
  static propTypes = {
    pushrules: PropTypes.array,
    isLoadingTable: PropTypes.string,
  };

  state = {
    recordId: null,
    dialogStatus: false,
    dialogType: 'create',
  };

  componentDidMount() {
    // 组件加载完成后，获取表单项的数据
    const fullName = pathResource.fullName.split('/')[1]
      ? pathResource.fullName.split('/')[1].trim()
      : '';
    document.title = intl.get(
      {
        id: 'code-assets.settingsPushRules.containers.root.PushRuleSettingsFullnameYunxiao',
        defaultMessage: '推送规则设置 · {fullName} · 云效 Codeup',
      },
      { fullName },
    );
    this.props.getPushRules();
    enterPage('Repo-Settings-PushRules', {
      sendPerf: false,
    });
  }

  handleRecord = (record, checkerName) => {
    record.rule_infos.forEach((item) => {
      if (typeof item === 'object' && item !== null) {
        if (item.checker_name === checkerName) {
          return item.extra_message;
        }
      }
    });
  };

  openDialog = (dialogType, recordId) => {
    this.setState({
      dialogStatus: true,
      recordId,
      dialogType,
    });
  };

  closeDialog = () => {
    this.setState({
      dialogStatus: false,
      recordId: null,
      dialogType: 'create',
    });
  };

  renderBranch = (value, index, record) => {
    return (
      <div>
        {record.ref_name}
        {record.ref_name === pathResource.defaultBranch && (
          <Tag className="ml10">
            {intl.get({
              id: 'code-assets.settingsPushRules.containers.root.DefaultBranch',
              defaultMessage: '默认分支',
            })}
          </Tag>
        )}

        {!!record.matches &&
          (record.matches.length > 0 ? (
            <Balloon.Tooltip
              trigger={
                <div>
                  <Tag className="ml10">
                    {record.matches.length}
                    {intl.get({
                      id: 'code-assets.settingsPushRules.containers.root.MatchingBranches',
                      defaultMessage: '个匹配分支',
                    })}
                  </Tag>
                </div>
              }
              align={'t'}
            >
              <div>
                {record.matches.map((item) => {
                  return <div>{item}</div>;
                })}
              </div>
            </Balloon.Tooltip>
          ) : null)}
      </div>
    );
  };

  renderRuleInfo = (value, index, record, key) => {
    if (record.inherited) {
      return (
        <Balloon.Tooltip
          align="t"
          text={
            key === 'commit_message_checker'
              ? intl.get({
                id: 'code-assets.settingsPushRules.containers.root.EnterpriseLevelCommentSubmissionRules',
                defaultMessage: '暂未支持企业级提交注释规则',
              })
              : intl.get({
                id: 'code-assets.settingsPushRules.containers.root.NotYetSupportEnterpriseLevel',
                defaultMessage: '暂未支持企业级提交邮箱规则',
              })
          }
          trigger={
            <span style={{ cursor: 'pointer' }}>
              {value ||
                intl.get({
                  id: 'code-assets.settingsPushRules.containers.root.No',
                  defaultMessage: '无',
                })}
            </span>
          }
        />
      );
    }
    return (
      <span>
        <Title
          trigger={
            <span>
              {value ||
                intl.get({
                  id: 'code-assets.settingsPushRules.containers.root.No',
                  defaultMessage: '无',
                })}
            </span>
          }
        >
          <div>
            {value ||
              intl.get({
                id: 'code-assets.settingsPushRules.containers.root.No',
                defaultMessage: '无',
              })}
          </div>
        </Title>
      </span>
    );
  };

  renderAction = (value, index, record) => {
    if (record.inherited) {
      return (
        <div>
          <Balloon.Tooltip
            align="tr"
            trigger={
              <Button type="primary" text disabled style={{ marginRight: 12 }}>
                {intl.get({
                  id: 'code-assets.settingsPushRules.containers.root.Editing',
                  defaultMessage: '编辑',
                })}
              </Button>
            }
            text={intl.get({
              id: 'code-assets.settingsPushRules.containers.root.ItIsInheritedFromThe',
              defaultMessage: '继承自企业推送规则设置，不可编辑，如需修改请联系企业管理员',
            })}
          />

          <Balloon.Tooltip
            align="tr"
            trigger={
              <Button type="primary" text disabled>
                {intl.get({
                  id: 'code-assets.settingsPushRules.containers.root.Delete',
                  defaultMessage: '删除',
                })}
              </Button>
            }
            text={intl.get({
              id: 'code-assets.settingsPushRules.containers.root.ItIsInheritedFromThe.1',
              defaultMessage: '继承自企业推送规则设置，不可删除，如需修改请联系企业管理员',
            })}
          />
        </div>
      );
    }
    return (
      <div>
        {/* <EditPushRule
          trigger={
            <Button type="primary" text style={{ marginRight: 12 }}>
              {intl.get({
                id: 'code-assets.settingsPushRules.containers.root.Editing',
                defaultMessage: '编辑',
              })}
            </Button>
          }
          id={record.id}
          {...this.props}
        /> */}
        <Button type="primary" text style={{ marginRight: 12 }} onClick={() => { this.openDialog('update', record.id); }}>
          {intl.get({
            id: 'code-assets.settingsPushRules.containers.root.Editing',
            defaultMessage: '编辑',
          })}
        </Button>
        <DeleteConfirm
          id={record.id}
          remove={this.props.remove}
          content={intl.get({
            id: 'code-assets.settingsPushRules.containers.root.PushRules',
            defaultMessage: '推送规则',
          })}
          trigger={
            <Button type="primary" text>
              {intl.get({
                id: 'code-assets.settingsPushRules.containers.root.Delete',
                defaultMessage: '删除',
              })}
            </Button>
          }
        />
      </div>
    );
  };

  renderCommitRuleInfo = (value, index, record) => {
    if (!value) {
      return intl.get({
        id: 'code-assets.settingsPushRules.containers.root.No',
        defaultMessage: '无',
      });
    }
    const { commit_check_level, commit_check_rules } = record;
    const arr = commit_check_rules.map((item) => commitCheckRuleObj[item]);
    const arrStr = arr.join('、');
    const text1 = intl.get(
      {
        id: 'code-assets.settingsPushRules.containers.root.CheckRuleArrstr',
        defaultMessage: '检查规则：{arrStr}',
      },
      { arrStr },
    );
    const text2 = intl.get(
      {
        id: 'code-assets.settingsPushRules.containers.root.LimitCommitchecklevelobjcommitcheck',
        defaultMessage: '限制级别：{commitCheckLevelObjCommitCheck}',
      },
      { commitCheckLevelObjCommitCheck: commitCheckLevelObj[commit_check_level] },
    );
    return (
      <Title
        trigger={
          <span>
            {text1};{text2}
          </span>
        }
        align="t"
      >
        <div>
          {text1}
          <br />
          {text2}
        </div>
      </Title>
    );
  };
  renderPrehookRuleInfo = (value, index, record) => {
    if (!value) {
      return intl.get({
        id: 'code-assets.settingsPushRules.containers.root.No',
        defaultMessage: '无',
      });
    }
    const { third_party_url, prehook_checker_type } = record;
    const checkText = prehookCheckLevelObj[prehook_checker_type];
    const timeoutText = intl.get(
      {
        id: 'code-assets.settingsPushRules.containers.root.TimeoutChecktext',
        defaultMessage: '超时处理：{checkText}',
      },
      { checkText },
    );
    const urlText = intl.get(
      {
        id: 'code-assets.settingsPushRules.containers.root.UrlThirdpartyurl',
        defaultMessage: 'URL 地址：{thirdPartyUrl}',
      },
      { thirdPartyUrl: third_party_url },
    );
    return (
      <Title
        trigger={
          <span>
            {urlText};{timeoutText}
          </span>
        }
        align="t"
      >
        <div>
          {urlText}
          <br />
          {timeoutText}
        </div>
      </Title>
    );
  };
  render() {
    const { pushrules, isLoadingTable } = this.props;
    const hasCreatedRule = pushrules && pushrules.find((rule) => !rule.inherited);

    return (
      <>
        <Section
          title={intl.get({
            id: 'code-assets.settingsPushRules.containers.root.PushRules',
            defaultMessage: '推送规则',
          })}
          description={intl.get({
            id: 'code-assets.settingsPushRules.containers.root.AllowsYouToCheckThe',
            defaultMessage: '支持在推送时对提交进行规则检查',
          })}
          operation={hasCreatedRule ? (
            <Tooltip
              trigger={
                <Button type="secondary" className="pushrules-extra" disabled onClick={() => { this.openDialog('create', null); }}>
                  <YunxiaoIcon type="add-fill" />
                  {intl.get({
                    id: 'code-assets.settingsPushRules.containers.root.CreateAPushRule',
                    defaultMessage: '新建推送规则',
                  })}
                </Button>
              }
              align="tr"
              text={intl.get({
                id: 'code-assets.settingsPushRules.containers.root.AFullBranchPushRule',
                defaultMessage: '已存在全量分支推送规则，自定义分支规则敬请期待',
              })}
            />
          ) : (
            <Button type="secondary" className="pushrules-extra" onClick={() => { this.openDialog('create', null); }}>
              <YunxiaoIcon type="add-fill" />
              {intl.get({
                id: 'code-assets.settingsPushRules.containers.root.CreateAPushRule',
                defaultMessage: '新建推送规则',
              })}
            </Button>
          )
          }
        >
          {!isLoadingTable ? (
            <div>
              <Perf page="Repo-Settings-PushRules" />
              {pushrules && pushrules.length > 0 ? (
                <YunxiaoTable dataSource={pushrules} hasBorder className="pushrules-table">
                  <YunxiaoTable.Column
                    width={120}
                    title={intl.get({
                      id: 'code-assets.settingsPushRules.containers.root.TargetBranch',
                      defaultMessage: '目标分支',
                    })}
                    cell={this.renderBranch}
                  />

                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsPushRules.containers.root.SubmitComments',
                      defaultMessage: '提交注释',
                    })}
                    // className="pushrules-rule-width"
                    dataIndex="commit_message_checker"
                    cell={(value, index, record) => {
                      return this.renderRuleInfo(value, index, record, 'commit_message_checker');
                    }}
                  />

                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsPushRules.containers.root.SubmitEmail',
                      defaultMessage: '提交邮箱',
                    })}
                    // className="pushrules-rule-width"
                    dataIndex="commit_email_checker"
                    cell={(value, index, record) => {
                      return this.renderRuleInfo(value, index, record, 'commit_email_checker');
                    }}
                  />

                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsPushRules.containers.root.ForcePush',
                      defaultMessage: '强制推送',
                    })}
                    width={100}
                    dataIndex="is_force_push_disable"
                    cell={(value) => {
                      return value
                        ? intl.get({
                          id: 'code-assets.settingsPushRules.containers.root.Prohibited',
                          defaultMessage: '禁止',
                        })
                        : intl.get({
                          id: 'code-assets.settingsPushRules.containers.root.No',
                          defaultMessage: '无',
                        });
                    }}
                  />

                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsPushRules.containers.root.TheCodeBelongsToThe',
                      defaultMessage: '代码属主检查',
                    })}
                    // className="pushrules-rule-width"
                    dataIndex="is_commit_check_enable"
                    cell={this.renderCommitRuleInfo}
                  />

                  <YunxiaoTable.Column
                    title={intl.get({
                      id: 'code-assets.settingsPushRules.containers.root.Operation',
                      defaultMessage: '操作',
                    })}
                    width={120}
                    cell={this.renderAction}
                  />
                </YunxiaoTable>
              ) : (
                <ListEmpty
                  type="card"
                  size="small"
                  content="暂无规则"
                  image="none"
                  className="no-content no-btns"
                />
              )}
            </div>
          ) : (
            <ListLoading style={{ textAlign: 'center' }} />
          )}
        </Section>
        {
          this.state.dialogStatus ?
            <PushRuleDialog
              recordId={this.state.recordId}
              dialogType={this.state.dialogType}
              isModalOpen={this.state.dialogStatus}
              closeDialog={this.closeDialog}
              {...this.props}
            />
            :
            null
        }
      </>
    );
  }
}

export default connect(
  (state) => state.project.projectSettings.settingsPushRules,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
